<template>
  <div>
    <div style="display: flex;">
     <!-- <searchDepart @treeSelectEmit="handleTreeSelect"></searchDepart>-->
      <div style="width: calc( 100%)">
        <!--引用表格-->
        <BasicTable @register="registerTable" :rowSelection="rowSelection"  @selection-change="selchange">
          <!--插槽:table标题-->
            <template #tableTitle>
                <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
              <a-button type="primary" @click="handleFreeze" preIcon="ant-design:edit-filled"> 冻结</a-button>
              <a-button type="primary" @click="handleunFreeze" preIcon="ant-design:edit-filled"> 解冻</a-button>
              <a-button type="primary" @click="batchHandleDelete" preIcon="ant-design:delete-filled"> 批量删除</a-button>
              <a-button type="primary" @click="handleDeleteList" preIcon="ant-design:delete-filled"> 已删除人员</a-button>
                <a-button  type="primary" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
                <j-upload-button  type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
              <a-tooltip  placement="top" title="压缩包的格式为zip，压缩包内的照片名字要符合“学/工号.jpg”的格式,例如123456.jpg" :autoAdjustOverflow="true">
                <div>
                <j-upload-button  type="primary" preIcon="ant-design:import-outlined" @click="importPhoto" tooltip="dkfjdk">导入照片</j-upload-button>
                </div>
            </a-tooltip>

              <a-button  type="primary" preIcon="ant-design:export-outlined" @click="onExportTemplate">下载导入模板</a-button>
              <a-button  type="primary" preIcon="ant-design:export-outlined" @click="handlePrintCard">打印卡片</a-button>
              <a-button  type="primary" preIcon="ant-design:export-outlined" @click="handlePrintCardnew">打印卡片(新)</a-button>
                <a-dropdown v-if="selectedRowKeys.length > 0">
                    <template #overlay>
                      <a-menu>
                        <a-menu-item key="1" @click="batchHandleDelete">
                          <Icon icon="ant-design:delete-outlined"></Icon>
                          删除
                        </a-menu-item>
                      </a-menu>
                    </template>
                   <!-- <a-button>批量操作
                      <Icon icon="mdi:chevron-down"></Icon>
                    </a-button>-->
              </a-dropdown>
              <!-- 高级查询 -->
              <!--<super-query :config="superQueryConfig" @search="handleSuperQuery" />-->
            </template>
            <template #infoSlot="{ record }">
              <div class="infoBox">
                  <img class="image"  @click="handleFile(baseApiUrl+'/'+VITE_GLOB_BUCKET_NAME+'/'+record.photo)" :src="baseApiUrl+'/'+VITE_GLOB_BUCKET_NAME+'/'+record.photo" v-if="record.photo" />
                  <img class="image" v-else src="https://ecard.dglemin.com.cn:55005/images/default_avatar.png" />
                  <div class="info">
                    <div class="name">{{record.name}}</div>
                    <div class="desc"><span>{{record.code}}</span></div>
                  </div>
              </div>
            </template>
             <template #paperSlot="{ record }">
              <div class="infoBox">
                  <div class="info">
                    <div class="">{{record.paperType_dictText}}</div>
                    <div class="desc"><span>{{record.paperNumber}}</span></div>
                  </div>
              </div>
            </template>
          <!-- <template #img="{ text }">
            <img :src="baseApiUrl+'/'+text" width="50px" height="100px" v-show="text"/>
          </template> -->
            <!--操作栏-->
            <template #action="{ record }">
              <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)"/>
            </template>
            <!--字段回显插槽-->
            <template v-slot:bodyCell="{ column, record, index, text }">
            </template>
        </BasicTable>
      </div>

    </div>

    <div style="display:none">
      <div id="printId">
        <div style="height:50px;"></div>
        <div style="text-align:center;height:126px;">
        <img style="text-align:center;width:90px;" :src="imgsrc"/>
        </div>

        <div v-if="position">
          <div style="height:20px;"></div>
          <div style="font-family: 楷体;font-weight:900;;font-size:40px;color: #353B73;text-align:center;letter-spacing: 5px;">{{cardPrintName}}</div>
        <div style="line-height:23px;font-family: 楷体;font-weight:900;;font-size:18px;color: #353B73;text-align:center">&nbsp;{{position}}</div>
        </div>
        <div v-if="!position">
          <div style="height:20px;"></div>
          <!--<div style="font-family: 楷体;font-weight:900;;font-size:50px;color: #353B73;text-align:center;letter-spacing: 5px;">{{cardPrintName}}</div>-->
          <div :style="[{'font-family': '楷体'},{'font-weight':'900'},{'font-size':fontsize},{'color':'#353B73'},{'text-align':'center'},{'letter-spacing': '5px'}]">{{cardPrintName}}</div>
          <div style="line-height:11px;font-family: 楷体;font-weight:900;;font-size:21px;color: #353B73;text-align:center">&nbsp;</div>
        </div>
        <div style="line-height:23px;font-family: 楷体;font-weight:900;;font-size:23px;color: #353B73;text-align:center;">{{cardPrintCode}}</div>
      </div>
      <div id="printId2">
        <div style="height:20px;"></div>
        <div style="height:128px;">
          <img style="margin-left:10px;text-align: center;width:92px;" :src="imgsrc"/>
        </div>
        <div style="height:80px;">
        <div style="height:15px;"></div>
          <div v-if="position">
        <div :style="[{'font-weight': '900'},{'font-family': '隶书'},{'margin-left':'30px'},{'width':'80%'},{'color': '#000'},{'text-align':'left'},{'font-size':'15px'}]">姓名：{{cardPrintName}}</div>
       <div style="margin-left:30px;font-family: 隶书;font-size:15px;font-weight:900;color: #000;text-align:left;width:80%">{{position}}</div>
        <div style="color: #000;text-align:left;font-size:15px;font-weight: 900 ;width:80%;margin-left:30px;font-family: 隶书">{{cardPrintCode1}}</div>
          </div>
          <div v-if="!position">
            <div style="height:12px;"></div>
            <div :style="[{'font-family': '隶书'},{'font-weight': '900'},{'margin-left':'30px'},{'width':'80%'},{'color': '#000'},{'text-align':'left'},{'font-size':'15px'}]">姓名：{{cardPrintName}}</div>
            <div style="color: #000;text-align:left;font-size:15px;font-weight: 900 ;width:80%;margin-left:30px;font-family: 隶书">{{cardPrintCode1}}</div>
          </div>
        </div>
        <div style="font-family:隶书;font-weight:900;color: #000;text-align:center;font-size:15px;width:100%;letter-spacing:2.5px">东华松山湖高级中学</div>
      </div>
    </div>
  
    <!-- 表单区域 -->
    <SsPersonModal @register="registerModal" @success="handleSuccess"></SsPersonModal>
    <SsPersonDeleteListModal @register="registerModalDeleteList" @success="handleSuccess"></SsPersonDeleteListModal>
    <SsCardModalByPerson @register="registerModalCard" @success="handleSuccess"></SsCardModalByPerson>

  </div>
</template>

<script lang="ts" name="baseinfo-ssPerson" setup>
  import {ref, reactive, computed, unref,watch} from 'vue';
  import {BasicTable, useTable, TableAction} from '/@/components/Table';
  import {useModal} from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage'
  import SsPersonModal from './components/SsPersonModal.vue'
  import SsPersonDeleteListModal from './components/SsPersonDeleteListModal.vue'
  import SsCardModalByPerson from './components/SsCardModalByPerson.vue'


  import searchDepart from '../components/searchDepart.vue'
  import {columns, searchFormSchema, superQuerySchema} from './SsPerson.data';
  import {
    list,
    deleteOne,
    batchDelete,
    getImportUrl,
    getExportUrl,
    freeze,
    unfreeze,
    getExportTemplateUrl, getImportPhotoUrl
  } from './SsPerson.api';

  import {list as listcard} from "/@/views/baseinfo/card/SsCard.api";
  import { downloadFile } from '/@/utils/common/renderUtils';
  import { useUserStore } from '/@/store/modules/user';
  import {useMethods} from "@/hooks/system/useMethods";
  import {useMessage} from "@/hooks/web/useMessage";
  import {useGlobSetting} from "@/hooks/setting";
  import {getAppEnvConfig} from "@/utils/env";
  import {createImgPreview} from "@/components/Preview";
  import dayjs from 'dayjs';
  const globSetting = useGlobSetting();
  const baseApiUrl = globSetting.domainUrl;
  const { handleExportXls, handleImportXls } = useMethods();
  const {VITE_GLOB_BUCKET_NAME} = getAppEnvConfig();


  const imgsrc = ref();
  const cardPrintName = ref();
  const cardPrintCode = ref();
  const cardPrintCode1 = ref();
  const fontSpace = ref();
  const fontsize = ref();
  const position = ref();
  const queryParam = reactive<any>({});
  const checkedKeys = ref<Array<string | number>>([]);
  const userStore = useUserStore();
  const { createMessage, createErrorModal,createWarningModal,createInfoModal } = useMessage();
  //注册model
  const [registerModal, {openModal}] = useModal();

  const [registerModalDeleteList, {openModal:openModalDeleteList}] = useModal();
  const [registerModalCard, {openModal:openModalCard}] = useModal();


  //注册table数据
  const { prefixCls,tableContext,onExportXls,onImportXls } = useListPage({
      tableProps:{
           title: '人员',
           api: list,
           columns,
           canResize:false,
           formConfig: {
              //labelWidth: 120,
              schemas: searchFormSchema,
              autoSubmitOnEnter:true,
              showAdvancedButton:true,
              fieldMapToNumber: [
              ],
              fieldMapToTime: [
              ],
            },
           actionColumn: {
               width: 220,
               fixed:'right'
            },
            beforeFetch: (params) => {
              return Object.assign(params, queryParam);
            },
      },
       exportConfig: {
            name:"人员",
            url: getExportUrl,
            params: queryParam,
          },
          importConfig: {
            url: getImportUrl,
            success: handleSuccessImport
          },
  })

  const [registerTable, {reload,getForm},{ rowSelection, selectedRowKeys }] = tableContext


  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);

  async function handleTreeSelect(e){
    console.log(e);
    let { getFieldsValue,setFieldsValue,submit } =  getForm()
    let data = getFieldsValue()
    data.departmentId = e[0]
    console.log(data);
    await setFieldsValue(data)
    await submit()
  }

   function onExportTemplate() {
    let realUrl = getExportTemplateUrl ;
     return handleExportXls("人员导入模板", realUrl, new Object());
  }
  function selchange(e){
    console.log(e);
    position.value=undefined;
    if(!e.rows)
      return;
    for(let i = 0;i<e.rows.length;i++){
      if(e.rows[i].photo){
        imgsrc.value=baseApiUrl+'/'+VITE_GLOB_BUCKET_NAME+'/'+e.rows[i].photo;
      }
      console.log(e)
      if(!e.rows[i].photo){
        let tempbase = baseApiUrl.replace("/jeecgboot","")
        imgsrc.value=tempbase+"/images/default_avatar.png";
      }
      console.log(imgsrc.value)


     // imgsrc.value= 'https://ecard.dglemin.com.cn:55005/jeecgboot/asc/photo/无标题_1718850912288.jpg';
     // imgsrc.value="https://ecard.dglemin.com.cn:55005/jeecgboot/asc/photo/181030_1721284642018.jpg";



      cardPrintName.value  = e.rows[i].name;
      if(e.rows[i].position) {
        cardPrintCode1.value = "编号：" + e.rows[i].code;
        cardPrintCode.value =e.rows[i].code;
      }
      else {
        cardPrintCode1.value = "学号：" + e.rows[i].code;
        cardPrintCode.value = e.rows[i].code;
      }
      if(e.rows[i].position)
      position.value = "职务："+e.rows[i].position;
      if(cardPrintName.value.length==2){
        fontSpace.value='10px';
        fontsize.value = '50px';

        }
      if(cardPrintName.value.length==3) {
        fontSpace.value = '7px';
        fontsize.value = '50px';
      }
      if(cardPrintName.value.length==4) {
        fontSpace.value = '0px';
        fontsize.value = '40px';
      }

    }
  }

  function importPhoto(file){

    //update-begin-author:taoyan date:20220507 for: erp代码生成 子表 导入地址是动态的
    let realUrl = getImportPhotoUrl;// typeof getImportFAOPIAOUrl === 'function' ? getImportFAOPIAOUrl() : getImportFAOPIAOUrl;
    if (realUrl) {
      return handleImportXls(file, realUrl, handleSuccessImport || reload);
      //update-end-author:taoyan date:20220507 for: erp代码生成 子表 导入地址是动态的
    } else {
      $message.createMessage.warn('没有传递 url 参数');
      return Promise.reject();
    }
  }
  function handleImportPhotoSuccess(){

  }
  function handleSuccessImport(data){
    //if(data.indexOf(""))
    createInfoModal({
      title: '上传信息',
      content: '' + data,
      maskClosable: true,
    });
    (selectedRowKeys.value = []) && reload();

  }

  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    reload();
  }
   /**
    * 新增事件
    */
  function handleAdd() {
     openModal(true, {
       isUpdate: false,
       showFooter: true,
     });
  }
   /**
    * 编辑事件
    */
  function handleEdit(record: Recordable) {
     openModal(true, {
       record,
       isUpdate: true,
       showFooter: true,
     });
   }
   /**
    * 详情
   */
  function handleDetail(record: Recordable) {
     openModal(true, {
       record,
       isUpdate: true,
       showFooter: false,
     });
   }

  function handleDeleteList() {
    openModalDeleteList(true, {
      isUpdate: true,
      showFooter: false,
    });
  }
  function handlePrintCardnew(){
    if(rowSelection.selectedRowKeys.length!=1){
      createMessage.warn("只能选中一个人员来打印")
      return;
    }
    let old = "printId2";
    let newn = "printId";
    onIframePrint(newn)
  }
  function handlePrintCard(){
    if(rowSelection.selectedRowKeys.length!=1){
      createMessage.warn("只能选中一个人员来打印")
      return;
    }
    let old = "printId2";
    let newn = "printId";
      onIframePrint(old)

  }

  function onIframePrint(p) {
    const printContentHtml = document.getElementById(p).innerHTML;
    const iframe = document.createElement("iframe");
    iframe.setAttribute(
      "style",
      "position:absolute;width:0px;height:0px;left:-500px;top:-500px;"
    );
    document.body.appendChild(iframe);
    iframe.contentDocument.write(printContentHtml);
    iframe.contentDocument.close();
    iframe.contentWindow.print();
    document.body.removeChild(iframe);
  }


   /**
    * 删除事件
    */
  async function handleDelete(record) {
     await deleteOne({id: record.id,deleteCard:true}, handleSuccess);
   }
   /**
    * 批量删除事件
    */
  async function batchHandleDelete() {
     await batchDelete({ids: selectedRowKeys.value}, handleSuccess);
   }

  async function handleFreeze() {
      await freeze({ids: selectedRowKeys.value}, handleSuccess);
  }
  async function handleunFreeze() {
    await unfreeze({ids: selectedRowKeys.value}, handleSuccess);
  }

  async function handleCard(record: Recordable) {

    let personid = record.id;
    let res = await listcard({personId:personid});
    console.log(res);
    if(res.records?.length>0){
      openModalCard(true, {
        record:res.records[0],
        recordPerson:record,
        isUpdate: true,
        showFooter: true,
      });
    }else{
      openModalCard(true, {
        recordPerson:record,
        isUpdate: false,
        showFooter: true,
      });
    }

  }




   /**
    * 成功回调
    */
  function handleSuccess() {
      (selectedRowKeys.value = []) && reload();
   }
   /**
      * 操作栏
      */
  function getTableAction(record){
       return [
         {
           label: '编辑',
           onClick: handleEdit.bind(null, record),
         },
         {
           label: '卡片管理',
           onClick: handleCard.bind(null, record),
         }
       ]
   }
     /**
        * 下拉操作栏
        */
  function getDropDownAction(record){
       return [
         {
           label: '详情',
           onClick: handleDetail.bind(null, record),
         }, {
           label: '删除',
           popConfirm: {
             title: '是否同时删除卡片',
             confirm: handleDelete.bind(null, record),
             cancel:handleCanel.bind(null, record),
             okText:"删除卡片",
             cancelText:"保留卡片",
             placement: 'topLeft',
           }
         }
       ]
   }
  async function handleCanel(record){
    await deleteOne({id: record.id,deleteCard:false}, handleSuccess);
  }


  function handleFile(file) {
    console.log(file);
    let tempArr = file.split('.')
    let imgList = ['png', 'jpg', 'gpeg', 'bmp', 'webp']
    let suffix = tempArr[tempArr.length - 1]
    let isImg = imgList.some((item) => {
      return item == suffix.toLowerCase()
    })
    if (isImg) {
      createImgPreview({imageList: [file], maskClosable: true});
    }else {
      window.open(file);
    }
  }

</script>

<style lang="less" scoped>
.infoBox{
  display: flex;
  .image{
    width: 50px;
    height: 50px;
    margin-right: 10px;
    border: 1px solid #f5f5f5;
  }
  .info{
    flex: 1;
    .name{
      font-size: 16px;
      color: #210000;
    }
    .desc{
      display: flex;
      justify-content: center;
      margin-top: 5px;
      span{
      }
    }
  }
}
.imgs{
  position: absolute;
  width:50%;
  height:50%;

}
.imgBox{
  position: relative;
  /* 目标宽高 */
  width: 40%;
  height: 30%;
  overflow: hidden;
}


</style>
